<template>
  <div class="partial-modify-container">
    <div class="fusion-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- Step 1 -->
        <div
          class="step-section"
          :class="{
            'active-step': currentStep === 1,
            'completed-step': currentStep > 1,
          }"
        >
          <div class="step-header" @click="setStep(1)">
            <span class="step-title">Step 1</span>
            <span class="step-desc">上传要改款的鞋款</span>
            <el-tooltip content="帮助信息" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
            <span v-if="currentStep > 1" class="step-status">
              <el-icon><Check /></el-icon>
            </span>
          </div>
          
          <div class="upload-section">
            <div class="image-preview" @click="triggerMainImageUpload">
              <div
                v-if="mainImage"
                class="preview-container"
              >
                <img :src="mainImage" alt="主图预览" class="preview-img" crossorigin="anonymous" />
                <div class="change-overlay">
                <el-icon><Plus /></el-icon>
                  <span>更换图片</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>

              <!-- 隐藏的上传组件 -->
              <el-upload
                class="hidden-upload"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                @change="handleMainImageChange"
                ref="mainImageUploadRef"
              />
            </div>

            <!-- 添加标记可选区域按钮 -->
            <div
              v-if="mainImage"
              class="mark-area"
              @click="showSelectionOptions(1)"
            >
              <el-icon><EditPen /></el-icon>
              <span>标记可选区域</span>
            </div>

          </div>
        </div>

        <!-- Step 2 -->
        <div
          class="step-section"
          :class="{
            'active-step': currentStep === 2,
            'completed-step': currentStep > 2,
            'disabled-step': currentStep < 2,
          }"
          style="margin-top: 30px;"
        >
          <div class="step-header" @click="currentStep >= 2 && setStep(2)">
            <span class="step-title">Step 2</span>
            <span class="step-desc">上传参考图片</span>
            <el-tooltip content="帮助信息" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
            <span v-if="currentStep > 2" class="step-status">
              <el-icon><Check /></el-icon>
            </span>
          </div>
          
          <div class="upload-section">
            <div class="image-preview" @click="triggerReferenceImageUpload">
              <div
                v-if="referenceImage"
                class="preview-container"
              >
                <img
                  :src="referenceImage"
                  alt="参考图预览"
                  class="preview-img"
                  crossorigin="anonymous"
                />
                <div class="change-overlay">
                  <el-icon><Plus /></el-icon>
                  <span>更换图片</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>

              <!-- 隐藏的上传组件 -->
              <el-upload
                class="hidden-upload"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                @change="handleReferenceImageChange"
                ref="referenceImageUploadRef"
              />
            </div>

            <!-- 添加标记可选区域按钮 -->
            <div
              v-if="referenceImage"
              class="mark-area"
              @click="showSelectionOptions(2)"
            >
              <el-icon><EditPen /></el-icon>
              <span>标记可选区域</span>
            </div>

          </div>
        </div>
      </div>

      <!-- 中间工作区域 -->
      <div class="work-area">
        <template v-if="!mainImage && !referenceImage">
          <div class="instructions-container">
            <div class="instructions-content">
              <h3>使用说明</h3>
              <ol>
                <li>请上传背景干净无杂物的产品图，单只鞋的正面图最佳</li>
                <li>请尽量保持主产品与参考图两款鞋子角度一致性以达到最佳生成效果</li>
                <li>可以使用标记可选区域功能，指定需要修改的区域</li>
              </ol>
            </div>
          </div>
        </template>

        <!-- 显示主图工作区 -->
        <Suspense v-else-if="isEditingMainImage">
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="mainImage"
                :original-image-name="mainImageName"
                @image-edited="handleMainImageEdited"
                @editing-completed="completeMainImageEditing"
                ref="mainImageWorkspaceRef"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>

        <!-- 显示参考图工作区 -->
        <Suspense v-else-if="isEditingReferenceImage">
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="referenceImage"
                :original-image-name="referenceImageName"
                @image-edited="handleReferenceImageEdited"
                @editing-completed="completeReferenceImageEditing"
                ref="referenceImageWorkspaceRef"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>

        <!-- 结果查看区域 -->
        <Suspense v-else-if="isViewingResults && mainImage">
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="mainImage"
                :original-image-name="mainImageName"
                :is-view-results="true"
                :result-images="generatedImages"
                @exit-results="exitResultsView"
                ref="resultsWorkspaceRef"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 文本描述 -->
        <div class="step-section" :class="{ 'active-step': currentStep === 3 }">
          <div class="step-header">
            <span class="step-title">Step 3</span>
            <span class="step-desc">文本描述</span>
          </div>

          <div class="text-input-section">
            <div class="text-area-wrapper">
              <el-input
                v-model="textDescription"
                type="textarea"
                :rows="4"
                placeholder="非必填~"
                resize="none"
              />
              <div class="text-actions">
                <el-button class="action-btn" @click="textDescription = ''">
                  <el-icon><Delete /></el-icon>
                  <span>清空</span>
                </el-button>
              </div>
            </div>
          </div>
        </div>


        <!-- 生成按钮 -->
        <el-button
          type="primary"
          class="generate-btn"
          @click="handleGenerate"
          :disabled="!canGenerate"
        >
          立即生成
        </el-button>

        <div class="nav-buttons">
          <el-button v-if="currentStep > 1" @click="prevStep">
            上一步
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主图本地预览弹窗 -->
    <el-dialog 
      v-model="showPreviewDialogMain" 
      title="主图预览" 
      width="800px" 
      :close-on-click-modal="false"
      @close="cancelMainPreview"
    >
      <div class="upload-modal-content">
        <div class="upload-area">
          <div v-if="previewImageMain" class="file-preview">
            <img :src="previewImageMain" alt="主图预览" class="preview-img" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>请先选择图片</span>
            <p class="upload-tip">支持 JPG、PNG 格式，最大 10MB</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelMainPreview">取消</el-button>
          <el-button type="primary" @click="confirmMainPreview" :disabled="!selectedFileMain">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 参考图本地预览弹窗 -->
    <el-dialog 
      v-model="showPreviewDialogReference" 
      title="参考图预览" 
      width="800px" 
      :close-on-click-modal="false"
      @close="cancelReferencePreview"
    >
      <div class="upload-modal-content">
        <div class="upload-area">
          <div v-if="previewImageReference" class="file-preview">
            <img :src="previewImageReference" alt="参考图预览" class="preview-img" />
          </div>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>请先选择图片</span>
            <p class="upload-tip">支持 JPG、PNG 格式，最大 10MB</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelReferencePreview">取消</el-button>
          <el-button type="primary" @click="confirmReferencePreview" :disabled="!selectedFileReference">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 主图编辑弹窗 -->
    <el-dialog 
      v-model="showEditDialogMain" 
      title="主图编辑" 
      width="50%" 
      :close-on-click-modal="false" 
      class="edit-dialog"
    >
      <div class="edit-modal-content">
        <Suspense>
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="mainImage"
                :original-image-name="mainImageName"
                @image-edited="handleMainImageEdited"
                @editing-completed="closeEditDialogMain"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialogMain">取消</el-button>
          <!-- <el-button type="primary" @click="closeEditDialogMain">确认编辑</el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 参考图编辑弹窗 -->
    <el-dialog 
      v-model="showEditDialogReference" 
      title="参考图编辑" 
      width="50%" 
      :close-on-click-modal="false" 
      class="edit-dialog"
    >
      <div class="edit-modal-content">
        <Suspense>
          <template #default>
            <div class="image-workspace-container">
              <ImageWorkspaceComp
                :image-url="referenceImage"
                :original-image-name="referenceImageName"
                @image-edited="handleReferenceImageEdited"
                @editing-completed="closeEditDialogReference"
              />
            </div>
          </template>
          <template #fallback>
            <div class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>加载中...</p>
            </div>
          </template>
        </Suspense>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialogReference">取消</el-button>
          <!-- <el-button type="primary" @click="closeEditDialogReference">确认编辑</el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 标记可选区域选项弹窗 -->
    <SelectionOptionsDialog
      v-model="showSelectionDialog"
      @select="handleSelectOption"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent, computed } from "vue";
import {
  Plus,
  QuestionFilled,
  Delete,
  Loading,
  Check,
  EditPen,
} from "@element-plus/icons-vue";
import type { UploadInstance } from "element-plus";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { uploadImage, feedbackImage, isUserLoggedIn, jbch } from "../../api/file";
import type { UploadImageResponse, JbchRequest } from "../../api/file";
import { useRouter } from "vue-router";
import axios from "axios";

// 异步加载图片工作区组件
const ImageWorkspaceComp = defineAsyncComponent(
  () => import("./ImageWorkspace.vue")
);

// 异步加载选择对话框组件
const SelectionOptionsDialog = defineAsyncComponent(
  () => import("../common/SelectionOptionsDialog.vue")
);

// 获取路由器
const router = useRouter();

// 状态管理
const mainImage = ref("");
const mainImageName = ref(""); // 保存上传后的主图文件名
const referenceImage = ref(""); // 添加参考图状态
const referenceImageName = ref(""); // 保存上传后的参考图文件名
const textDescription = ref("");
const imaginationStrength = ref(5); // 默认中间值
const currentStep = ref(1);

// 添加编辑状态变量
const isEditingMainImage = ref(false);
const isEditingReferenceImage = ref(false);

// 主图本地预览弹窗相关状态
const showPreviewDialogMain = ref(false);
const previewImageMain = ref('');
const selectedFileMain = ref<File | null>(null);

// 参考图本地预览弹窗相关状态
const showPreviewDialogReference = ref(false);
const previewImageReference = ref('');
const selectedFileReference = ref<File | null>(null);

// 主图编辑弹窗相关状态
const showEditDialogMain = ref(false);

// 参考图编辑弹窗相关状态
const showEditDialogReference = ref(false);

// 结果查看相关
const isViewingResults = ref(false);
const generatedImages = ref<string[]>([]);
const mainImageWorkspaceRef = ref(null);
const referenceImageWorkspaceRef = ref(null);
const resultsWorkspaceRef = ref(null);

// 引用上传组件
const mainImageUploadRef = ref<UploadInstance | null>(null);
const referenceImageUploadRef = ref<UploadInstance | null>(null); // 添加参考图上传组件引用

// 计算属性
const canGenerate = computed(() => {
  return (
    !!mainImage.value &&
    !!mainImageName.value &&
    !!referenceImage.value &&
    !!referenceImageName.value
  );
});

// 触发重新上传主图
const triggerMainImageUpload = () => {
  if (mainImageUploadRef.value) {
    const uploadEl = mainImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector(
      'input[type="file"]'
    ) as HTMLInputElement;
    if (fileInput) {
      fileInput.click();
    }
  }
};

// 触发重新上传参考图
const triggerReferenceImageUpload = () => {
  if (referenceImageUploadRef.value) {
    const uploadEl = referenceImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector(
      'input[type="file"]'
    ) as HTMLInputElement;
    if (fileInput) {
      fileInput.click();
    }
  }
};

// 压缩图片
const compressImage = (file: File): Promise<File> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const img = new Image();
      img.src = e.target?.result as string;

      img.onload = () => {
        const canvas = document.createElement("canvas");
        let width = img.width;
        let height = img.height;

        // 限制最大尺寸为1600px
        const maxSize = 1600;
        if (width > height && width > maxSize) {
          height = Math.round((height * maxSize) / width);
          width = maxSize;
        } else if (height > maxSize) {
          width = Math.round((width * maxSize) / height);
          height = maxSize;
        }

        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");
        ctx?.drawImage(img, 0, 0, width, height);

        // 压缩为80%质量的JPEG
        canvas.toBlob(
          (blob) => {
            if (blob) {
              const compressedFile = new File([blob], file.name, {
                type: "image/jpeg",
                lastModified: Date.now(),
              });
              resolve(compressedFile);
            } else {
              reject(new Error("压缩失败"));
            }
          },
          "image/jpeg",
          0.8
        );
      };

      img.onerror = () => {
        reject(new Error("图片加载失败"));
      };
    };

    reader.onerror = () => {
      reject(new Error("文件读取失败"));
    };
  });
};

// 封装文件上传和回显流程
const uploadFile = (
  file: File,
  type: "input" | "output",
  callback?: (imageUrl: string, imageName?: string) => void
) => {
  // 检查用户是否已登录
  if (!isUserLoggedIn()) {
    ElMessageBox.confirm(
      "您需要登录才能上传图片。是否现在登录？",
      "未登录提示",
      {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        // 保存当前页面路径，登录后可以返回
        localStorage.setItem(
          "redirectAfterLogin",
          router.currentRoute.value.fullPath
        );
        // 导航到登录页
        router.push("/login");
      })
      .catch(() => {
        ElMessage.info("您可以继续使用本地图片预览功能，但无法保存到服务器");
      });

    // 仍然显示本地预览
    const reader = new FileReader();
    reader.onload = (e) => {
      if (callback && e.target?.result) {
        callback(e.target.result as string);
      }
    };
    reader.readAsDataURL(file);

    return;
  }

  // 显示加载提示
  const loading = ElLoading.service({
    lock: true,
    text: "图片上传中...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  // 检查文件大小，如果超过10MB则压缩
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.warning("图片过大，正在压缩...");
    compressImage(file)
      .then((compressedFile) => {
        doUpload(compressedFile);
      })
      .catch((err) => {
        ElMessage.error("图片压缩失败：" + err.message);
        loading.close();
      });
  } else {
    doUpload(file);
  }

  function doUpload(fileToUpload: File) {
    // 再次验证token
    const currentToken = localStorage.getItem("token");
    console.log("上传前验证 token:", currentToken);

    // 1. 调用上传API
    uploadImage(fileToUpload)
      .then((response: any) => {
        console.log("Upload successful response:", response);
        if (response.code === 0 || response.code === 200) {
          const imageData = response.data as UploadImageResponse;
          console.log("上传成功，获取到的图片ID:", imageData.id);

          // 保存图片ID
          const imageId = imageData.id;

          // 2. 调用回显API获取图片URL
          return feedbackImage(imageId).then((feedbackResponse) => {
            // 返回成功响应和图片ID
            return { response: feedbackResponse, imageId };
          });
        } else {
          // 如果是数据库编码错误，我们仍然尝试使用本地图片
          if (response.code === 423) {
            console.warn("上传成功但服务器日志记录失败，使用本地图片预览");
            if (callback) callback(URL.createObjectURL(fileToUpload));
            ElMessage.warning("图片已保存但可能无法从服务器获取，使用本地预览");
            return Promise.reject(new Error("server_log_error"));
          } else if (response.code === 401) {
            console.error("401错误 - 认证失败:", response);
            console.log(
              "当前localStorage中的token:",
              localStorage.getItem("token")
            );

            // 登录已过期或无效
            ElMessageBox.confirm(
              `您的登录状态异常，需要重新登录。错误信息: ${
                response.msg || "账号未登录"
              }`,
              "登录状态异常",
              {
                confirmButtonText: "去登录",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                // 清除无效的token
                localStorage.removeItem("token");
                // 保存当前页面路径，登录后可以返回
                localStorage.setItem(
                  "redirectAfterLogin",
                  router.currentRoute.value.fullPath
                );
                // 导航到登录页
                router.push("/login");
              })
              .catch(() => {
                ElMessage.info(
                  "您可以继续使用本地图片预览功能，但无法保存到服务器"
                );
              });

            // 仍然使用本地预览
            if (callback) callback(URL.createObjectURL(fileToUpload));
            return Promise.reject(new Error("login_required"));
          }
          throw new Error(response.msg || "上传失败");
        }
      })
      .then((result: any) => {
        if (!result) return;

        const { response, imageId } = result;
        if (response.code === 0 || response.code === 200) {
          // 获取到图片URL
          const imageUrl = response.data;
          if (callback) callback(imageUrl, imageId.toString());

          ElMessage.success("图片上传成功");
        } else {
          throw new Error(response.msg || "获取图片地址失败");
        }
      })
      .catch((error: any) => {
        if (
          error.message === "server_log_error" ||
          error.message === "login_required"
        ) {
          // 已经处理过了，不需要额外显示错误
          return;
        }

        console.error("图片上传失败:", error);
        // 如果是网络错误，提供重试选项
        if (
          error.message.includes("Network Error") ||
          error.message.includes("timeout")
        ) {
          ElMessage.error({
            message: "网络连接失败，请检查网络设置",
            duration: 5000,
          });
        } else {
          // 添加更详细的错误信息
          let errorMsg = error.message || "未知错误";
          if (error.response) {
            errorMsg += ` (状态码: ${error.response.status})`;
            if (error.response.data) {
              errorMsg += ` - ${JSON.stringify(error.response.data)}`;
            }
          }

          ElMessage.error({
            message: "图片上传失败: " + errorMsg,
            duration: 5000,
          });
        }
      })
      .then(() => {
        // 确保loading会关闭
        loading.close();
      });
  }
};

// 主图预览弹窗相关方法
const confirmMainPreview = () => {
  if (!selectedFileMain.value) return;
  uploadFile(selectedFileMain.value, 'input', (_, imageId) => {
    if (imageId) mainImageName.value = imageId;
    showEditDialogMain.value = true;
  });
  mainImage.value = previewImageMain.value;
  showPreviewDialogMain.value = false;
  // 清空文件输入框
  if (mainImageUploadRef.value) {
    const uploadEl = mainImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector('input[type="file"]') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  }
  selectedFileMain.value = null;
  previewImageMain.value = '';
};

const cancelMainPreview = () => {
  showPreviewDialogMain.value = false;
  // 清空文件输入框
  if (mainImageUploadRef.value) {
    const uploadEl = mainImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector('input[type="file"]') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  }
  selectedFileMain.value = null;
  previewImageMain.value = '';
};

// 参考图预览弹窗相关方法
const confirmReferencePreview = () => {
  if (!selectedFileReference.value) return;
  uploadFile(selectedFileReference.value, 'input', (_, imageId) => {
    if (imageId) referenceImageName.value = imageId;
    showEditDialogReference.value = true;
  });
  referenceImage.value = previewImageReference.value;
  showPreviewDialogReference.value = false;
  // 清空文件输入框
  if (referenceImageUploadRef.value) {
    const uploadEl = referenceImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector('input[type="file"]') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  }
  selectedFileReference.value = null;
  previewImageReference.value = '';
};

const cancelReferencePreview = () => {
  showPreviewDialogReference.value = false;
  // 清空文件输入框
  if (referenceImageUploadRef.value) {
    const uploadEl = referenceImageUploadRef.value.$el as HTMLElement;
    const fileInput = uploadEl.querySelector('input[type="file"]') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  }
  selectedFileReference.value = null;
  previewImageReference.value = '';
};

// 编辑弹窗相关方法
const closeEditDialogMain = () => {
  showEditDialogMain.value = false;
};

const closeEditDialogReference = () => {
  showEditDialogReference.value = false;
};

// 处理主图片上传
const handleMainImageChange = (file: any) => {
  // 验证文件类型和大小
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB');
    return;
  }

  // 设置选中的文件和预览图片
  selectedFileMain.value = file.raw;
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImageMain.value = e.target?.result as string;
    showPreviewDialogMain.value = true;
  };
  reader.readAsDataURL(file.raw);
};

// 将dataURL转换为Blob对象
const dataURLtoBlob = (dataURL: string) => {
  const parts = dataURL.split(';base64,')
  const contentType = parts[0].split(':')[1]
  const raw = window.atob(parts[1])
  const uInt8Array = new Uint8Array(raw.length)
  
  for (let i = 0; i < raw.length; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  
  return new Blob([uInt8Array], { type: contentType })
}

// 处理主图编辑完成
const handleMainImageEdited = (editedImageUrl: string, imageName?: string) => {
  // 更新主图显示
  mainImage.value = editedImageUrl;
  
  // 如果直接收到图片名称参数，则直接更新
  if (imageName) {
    console.log('从ImageWorkspace接收到主图片名称:', imageName);
    mainImageName.value = imageName;
    // 不要关闭编辑状态，等待用户点击完成编辑按钮
    // isEditingMainImage.value = false;
    // currentStep.value = 2;
    return;
  }
  
  // 如果是base64格式，需要上传到服务器
  if (editedImageUrl.startsWith('data:image')) {
    const blob = dataURLtoBlob(editedImageUrl);
    const file = new File([blob], 'edited-main-image.png', { type: 'image/png' });
    
    uploadFile(file, 'input', (imageUrl, imageName) => {
      console.log('编辑后主图上传成功:', imageUrl, '图片名称:', imageName);
      if (imageName) {
        mainImageName.value = imageName; // 更新图片名称为编辑后的
      }
      // 不要关闭编辑状态，等待用户点击完成编辑按钮
      // isEditingMainImage.value = false;
      // currentStep.value = 2;
    });
  } else {
    // 如果是服务器URL，尝试从URL中提取图片名称
    const urlParts = editedImageUrl.split('?');
    if (urlParts.length > 1) {
      const params = new URLSearchParams(urlParts[1]);
      const imageName = params.get('name');
      if (imageName) {
        console.log('从服务器URL提取的主图片名称:', imageName);
        mainImageName.value = imageName; // 更新图片名称
      }
    }
    // 不要关闭编辑状态，等待用户点击完成编辑按钮
    // isEditingMainImage.value = false;
    // currentStep.value = 2;
  }
};

// 添加完成主图编辑的方法
const completeMainImageEditing = () => {
  isEditingMainImage.value = false;
  currentStep.value = 2;
}

// 处理参考图片上传
const handleReferenceImageChange = (file: any) => {
  // 验证文件类型和大小
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB');
    return;
  }

  // 设置选中的文件和预览图片
  selectedFileReference.value = file.raw;
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImageReference.value = e.target?.result as string;
    showPreviewDialogReference.value = true;
  };
  reader.readAsDataURL(file.raw);
};

// 处理参考图编辑完成
const handleReferenceImageEdited = (editedImageUrl: string, imageName?: string) => {
  // 更新参考图显示
  referenceImage.value = editedImageUrl;
  
  // 如果直接收到图片名称参数，则直接更新
  if (imageName) {
    console.log('从ImageWorkspace接收到参考图片名称:', imageName);
    referenceImageName.value = imageName;
    // 不要关闭编辑状态，等待用户点击完成编辑按钮
    // isEditingReferenceImage.value = false;
    // currentStep.value = 3;
    return;
  }
  
  // 如果是base64格式，需要上传到服务器
  if (editedImageUrl.startsWith('data:image')) {
    const blob = dataURLtoBlob(editedImageUrl);
    const file = new File([blob], 'edited-reference-image.png', { type: 'image/png' });
    
    uploadFile(file, 'input', (imageUrl, imageName) => {
      console.log('编辑后参考图上传成功:', imageUrl, '图片名称:', imageName);
      if (imageName) {
        referenceImageName.value = imageName; // 更新图片名称为编辑后的
      }
      // 不要关闭编辑状态，等待用户点击完成编辑按钮
      // isEditingReferenceImage.value = false;
      // currentStep.value = 3;
    });
  } else {
    // 如果是服务器URL，尝试从URL中提取图片名称
    const urlParts = editedImageUrl.split('?');
    if (urlParts.length > 1) {
      const params = new URLSearchParams(urlParts[1]);
      const imageName = params.get('name');
      if (imageName) {
        console.log('从服务器URL提取的参考图片名称:', imageName);
        referenceImageName.value = imageName; // 更新图片名称
      }
    }
    // 不要关闭编辑状态，等待用户点击完成编辑按钮
    // isEditingReferenceImage.value = false;
    // currentStep.value = 3;
  }
};

// 添加完成参考图编辑的方法
const completeReferenceImageEditing = () => {
  isEditingReferenceImage.value = false;
  currentStep.value = 3;
}

// 退出结果查看模式
const exitResultsView = () => {
  isViewingResults.value = false;
};

// 添加标记区域函数
const handleMarkArea = (step: number) => {
  // 确保当前处于正确的步骤
  if (currentStep.value !== step) {
    setStep(step);
  }
  
  // 设置编辑状态
  if (step === 1) {
    isEditingMainImage.value = true;
    isEditingReferenceImage.value = false;
  } else {
    isEditingMainImage.value = false;
    isEditingReferenceImage.value = true;
  }

  // 使用setTimeout确保DOM更新后调用工具函数
  setTimeout(() => {
    // 根据当前步骤选择对应的工作区组件
    const workspaceRef =
      step === 1
        ? mainImageWorkspaceRef.value
        : referenceImageWorkspaceRef.value;

    // 调用工作区的标记可选功能
    if (workspaceRef) {
      // @ts-ignore
      workspaceRef.selectTool("mask");
    }
  }, 100); // 给DOM一点时间更新
};

// 处理生成按钮点击
const handleGenerate = async () => {
  if (!canGenerate.value) {
    ElMessage.warning("请先上传鞋款图片和参考图片");
    return;
  }

  // 验证用户登录
  if (!isUserLoggedIn()) {
    ElMessageBox.confirm(
      "您需要登录才能使用生成功能。是否现在登录？",
      "未登录提示",
      {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).then(() => {
      localStorage.setItem(
        "redirectAfterLogin",
        router.currentRoute.value.fullPath
      );
      router.push("/login");
    });
    return;
  }

  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "正在生成图片，请稍候...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    console.log("使用的参数:", {
      主图: mainImageName.value,
      参考图: referenceImageName.value,
      描述: textDescription.value || "自动改款",
      想象力: imaginationStrength.value,
    });

    // 准备请求参数
    const requestData: JbchRequest = {
      majorId: parseInt(mainImageName.value),
      minorId: parseInt(referenceImageName.value),
      prompt: textDescription.value || "自动改款",
      isMask: 2, // 默认使用二图蒙版
    };

    // 调用封装的API函数
    const response = await jbch(requestData);

    // 处理成功响应
    if (response.code === 0 || response.code === 200) {
      // 提取生成的图片URL
      const result = response.data;
      
      if (result && result.viewUrls && Array.isArray(result.viewUrls)) {
        generatedImages.value = result.viewUrls;

        // 显示结果
        if (generatedImages.value.length > 0) {
          isViewingResults.value = true;

          // 如果有mainImageWorkspaceRef，调用其showResults方法
          if (mainImageWorkspaceRef.value) {
            // @ts-ignore
            mainImageWorkspaceRef.value.showResults(generatedImages.value);
          }

          ElMessage.success("图片生成成功");
        } else {
          ElMessage.warning("生成成功但未获得图片");
        }
      } else {
        ElMessage.warning("生成响应格式异常");
      }
    } else {
      // 处理特定的错误码
      if (response.code === 1013) {
        throw new Error("请先选择需要更改的区域！");
      } else {
        throw new Error(response.msg || "生成图片失败");
      }
    }
  } catch (error: any) {
    console.error("图像生成失败:", error);
    ElMessage.error("生成失败: " + (error.message || "未知错误"));
  } finally {
    loadingInstance.close();
  }
};

// 添加步骤控制函数
const setStep = (step: number) => {
  if (
    step === 1 ||
    (step === 2 && mainImage.value) ||
    (step === 3 && mainImage.value && referenceImage.value)
  ) {
    currentStep.value = step;
  }
};

// 添加前一步函数
const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 标记可选区域选项弹窗相关方法
const showSelectionDialog = ref(false);
const currentMarkStep = ref(1);

// 显示标记可选区域选项
const showSelectionOptions = (step: number) => {
  // 保存当前步骤
  currentMarkStep.value = step;
  
  // 确保当前处于正确的步骤
  if (currentStep.value !== step) {
    setStep(step);
  }
  
  // 显示选项对话框
  showSelectionDialog.value = true;
};

// 处理选项选择
const handleSelectOption = (option: string) => {
  showSelectionDialog.value = false;
  
  // 设置编辑状态
  if (currentMarkStep.value === 1) {
    isEditingMainImage.value = true;
    isEditingReferenceImage.value = false;
  } else {
    isEditingMainImage.value = false;
    isEditingReferenceImage.value = true;
  }
  
  // 使用setTimeout确保DOM更新后调用工具函数
  setTimeout(() => {
    // 根据当前步骤选择对应的工作区组件
    const workspaceRef =
      currentMarkStep.value === 1
        ? mainImageWorkspaceRef.value
        : referenceImageWorkspaceRef.value;

    if (workspaceRef) {
      // 根据选项打开不同工具
      if (option === 'brush') {
        // 涂抹选区 - 使用mask工具
        // @ts-ignore
        workspaceRef.openToolModal('mask');
      } else if (option === 'smart') {
        // 智能选区 - 使用smartSelect工具
        // @ts-ignore
        workspaceRef.selectTool('smartSelect');
      }
    }
  }, 100);
};
</script>

<style scoped>
.partial-modify-container {
  width: 100%;
  height: 100vh;
  background: transparent;
  color: #fff;
  padding: 10px;
  position: relative;
  z-index: 1;
  margin-left: 80px;
  overflow: hidden;
}

/* 添加背景容器 */
.partial-modify-container::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("@/assets/bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: -1;
}

.fusion-content {
  display: flex;
  gap: 10px;
  height: calc(100vh - 20px);
  padding: 10px;
  max-width: calc(100vw - 100px);
  position: relative;
  z-index: 2;
  overflow: hidden;
}

.left-panel {
  width: 270px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 10px;
  backdrop-filter: blur(10px);
  overflow-y: auto;
  max-height: 100%;
}

.work-area {
  flex: 1;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.right-panel {
  width: 280px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 10px;
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 100%;
  overflow-y: auto;
}

.step-section {
  margin-bottom: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.active-step {
  box-shadow: 0 0 15px rgba(0, 163, 255, 0.3);
  background: rgba(0, 163, 255, 0.05);
}

.step-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding: 6px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.step-header:hover {
  background: rgba(255, 255, 255, 0.1);
}

.step-title {
  color: #c8ad7f;
  font-weight: bold;
}

.upload-section {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 20px;
}

.text-input-section {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 20px;
}

.image-preview {
  width: 100%;
  aspect-ratio: 4/3;
  border-radius: 6px;
  border: 1px dashed rgba(255, 255, 255, 0.2);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.2);
}

.image-preview:hover {
  border-color: #00A3FF;
  background: rgba(0, 163, 255, 0.1);
}

.preview-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.change-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.change-overlay .el-icon {
  font-size: 24px;
  color: white;
  margin-bottom: 8px;
}

.change-overlay span {
  color: white;
  font-size: 14px;
}

.preview-container:hover .change-overlay {
  opacity: 1;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.6);
}

.upload-placeholder .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-placeholder span {
  font-size: 14px;
}

.hidden-upload {
  display: none;
}

/* 添加标记区域的样式 */
.mark-area {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 20px;
  background: rgba(0, 163, 255, 0.1);
  border: 1px solid rgba(0, 163, 255, 0.3);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 15px;
  font-size: 14px;
  font-weight: 500;
  color: #c8ad7f;;
}

.mark-area:hover {
  background: rgba(0, 163, 255, 0.2);
  border-color: rgba(0, 163, 255, 0.5);
  transform: translateY(-2px);
}

.mark-area .el-icon {
  font-size: 16px;
  color: #c8ad7f;;
}

.instructions-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.instructions-content {
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  padding: 15px 20px;
  max-width: 500px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.instructions-content h3 {
  color: #c8ad7f;
  font-size: 18px;
  margin-bottom: 12px;
  text-align: center;
}

.instructions-content ol {
  list-style: none;
  padding: 0;
  margin: 0;
  counter-reset: instruction-counter;
}

.instructions-content li {
  color: #c8ad7f;
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 10px;
  padding-left: 28px;
  position: relative;
  counter-increment: instruction-counter;
}

.instructions-content li::before {
  content: counter(instruction-counter);
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  height: 20px;
  background: #c8ad7f;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
}

.usage-guide {
  color: #c8ad7f;
  padding: 15px;
}

.usage-guide ol {
  padding-left: 20px;
}

.usage-guide li {
  margin-bottom: 10px;
}

.params-section {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 20px;
}

.param-item {
  margin-bottom: 15px;
}

.model-selection {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 20px;
  height: 400px;
}

.generate-btn {
  width: 100%;
  height: 40px;
  background: linear-gradient(90deg, #c8ad7f 0%, #ffe7b2 100%);
  border: none;
  border-radius: 20px;
  font-size: 16px;
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px #c8ad7f33;
  transition: background 0.2s, color 0.2s;
}

.generate-btn:disabled {
  background: linear-gradient(90deg, #e0cfa0 0%, #f5e6c3 100%);
  opacity: 0.7;
  color: #fff;
}

.generate-btn:hover:not(:disabled) {
  background: linear-gradient(90deg, #ffe7b2 0%, #c8ad7f 100%);
  color: #c8ad7f;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255, 255, 255, 0.7);
}

.loading-icon {
  font-size: 36px;
  animation: rotate 1.5s linear infinite;
  margin-bottom: 16px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.image-workspace-container {
  width: 100%;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-workspace {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: rgba(255, 255, 255, 0.5);
}

.empty-message .el-icon {
  font-size: 48px;
}

.empty-message p {
  font-size: 16px;
  margin: 0;
}

.text-area-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.text-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: #fff;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.action-btn .el-icon {
  font-size: 16px;
}

:deep(.el-textarea__inner) {
  background-color: transparent;
  border: none;
  color: #fff;
  resize: none;
}

:deep(.el-textarea__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

:deep(.el-button.action-btn) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: #fff;
}

:deep(.el-button.action-btn:hover) {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: #fff;
}

:deep(.el-button.action-btn:focus) {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: #fff;
}

:deep(.el-slider__runway) {
  background: #f5e6c3 !important;
}

:deep(.el-slider__bar) {
  background: linear-gradient(90deg, #c8ad7f 0%, #ffe7b2 100%) !important;
}

:deep(.el-slider__button) {
  border-color: #c8ad7f !important;
  background: #fffbe6 !important;
  box-shadow: 0 0 0 2px #c8ad7f33;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload-dragger) {
  background-color: transparent;
  border: none;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

:deep(.el-collapse) {
  border: none;
  background: transparent;
}

:deep(.el-collapse-item__header) {
  background: transparent;
  color: #c8ad7f;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-collapse-item__content) {
  background: transparent;
  color: #fff;
  padding: 0;
}

.step-navigation {
  display: flex;
  justify-content: space-between;
  margin-top: auto;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.upload-area {
  width: 80%;
  height: 400px;
  border: 2px dashed transparent;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.03);
  margin: 0 auto;
}

.upload-area:hover {
  border-color: transparent;
}

.file-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.file-preview .preview-img {
  max-width: 95%;
  max-height: 90%;
  object-fit: contain;
  border: none;
}

.upload-tip {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 编辑弹框样式 */
.edit-dialog :deep(.el-dialog) {
  border: 2px solid #c8ad7f;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(200, 173, 127, 0.15);
  background: rgba(30, 30, 30, 0.98);
  color: #fff;
  max-width: 95vw;
  max-height: 95vh;
}

.edit-modal-content {
  height: 60vh;
  overflow: hidden;
}

.edit-modal-content .image-workspace-container {
  height: 100%;
  width: 100%;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border: 2px solid #c8ad7f;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(200, 173, 127, 0.15);
  background: rgba(30, 30, 30, 0.98);
  color: #fff;
}

.upload-modal-content {
  padding: 20px 0;
}
</style> 
